<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search peopleInfoSearch" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="公司名称" prop="companyId">
            <el-select
              class="slese"
              v-model="queryParams.companyId"
              placeholder="请选择公司"
              ref="selectRef"
              @change="companyChanged($event)"
              style="width: 240px;"
              :clearable="useCompany.companyId?false:true"
            >
              <el-option
                class="communityDropdown"
                v-for="item in companyList"
                :key="item.companyId"
                :label="item.companyName"
                :value="item.companyId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目名称" prop="projectId">
            <el-select class="slese" v-model="queryParams.projectId" placeholder="请选择项目" ref="selectRef" clearable style="width: 240px;">
              <el-option
                class="communityDropdown"
                v-for="item in projectList"
                :key="item.projectId"
                :label="item.projectName"
                :value="item.projectId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="入职时间" prop="entryTime">
            <el-date-picker clearable v-model="queryParams.entryTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择入职时间" />
          </el-form-item> -->
          <el-form-item label="是否缴纳社保" prop="isSbPayment">
            <el-select v-model="queryParams.isSbPayment" class="m-2" placeholder="请选择是否缴纳社保" clearable style="width: 240px">
              <el-option v-for="dict in data_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="社保缴纳日期" prop="sbPaymentDate">
            <el-date-picker clearable
              v-model="queryParams.sbPaymentDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择社保缴纳日期"
            />
          </el-form-item> -->
          <!-- <el-form-item label="合同到期时间" prop="contractEndDate">
            <el-date-picker clearable
              v-model="queryParams.contractEndDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择合同到期时间"
            />
          </el-form-item> -->
          <!-- <el-form-item label="合同年限" prop="contractDuration">
            <el-input v-model="queryParams.contractDuration" placeholder="请输入合同年限" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <!-- <el-form-item label="岗位id" prop="postId">
            <el-input v-model="queryParams.postId" placeholder="请输入岗位id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <div class="flex flex-col items-start gap-4">
              <el-segmented v-model="peopleTypeValue" :options="options" size="default" />
            </div>
          </el-col>
          <el-col :span="1.5" v-show="peopleTypeValue=='在职人员'">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:peopleInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:peopleInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:peopleInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:peopleInfo:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Upload" @click="importData">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExportTemplate">导出模板</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="peopleInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="公司名称" align="center" prop="companyName" fixed />
        <el-table-column label="项目名称" align="center" prop="projectName" width="200" fixed />
        <el-table-column label="姓名" align="center" prop="name" fixed />
        <el-table-column label="性别" align="center" prop="sex" />
        <el-table-column label="入职时间" align="center" prop="entryTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.entryTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="岗位" align="center" prop="post" width="120" />
        <el-table-column label="身份证号" align="center" prop="identityCard" width="170" />
        <el-table-column label="联系电话" align="center" prop="phone" width="120" />
        <el-table-column label="家庭住址" align="center" prop="address" width="180" />
        <el-table-column label="是否缴纳社保" align="center" prop="isSbPayment">
          <template #default="scope">
            <dict-tag :options="data_yes_no" :value="scope.row.isSbPayment" />
          </template>
        </el-table-column>
        <el-table-column label="社保缴纳日期" align="center" prop="sbPaymentDate" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.sbPaymentDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="银行卡号" align="center" prop="bankNumber" width="160" />
        <el-table-column label="合同签署次数" align="center" prop="contractCount" />
        <el-table-column label="合同年限" align="center" prop="contractDuration">
          <template #default="scope">
            <span>{{ scope.row.contractDuration ? scope.row.contractDuration + '年' : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同到期时间" align="center" prop="contractEndDate" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.contractEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!-- 离职人员 -->
        <el-table-column v-if="peopleTypeValue=='离职人员'" label="离职时间" align="center" prop="resignationTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.resignationTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!-- 在职人员 -->
        <el-table-column label="物业证件" align="center" prop="certificateName" v-if="peopleTypeValue=='在职人员'" width="180" />
        <el-table-column label="派遣流程" align="center" prop="dispatchStatus" v-if="peopleTypeValue=='在职人员'">
          <template #default="scope">
            <dict-tag :options="data_yes_no" :value="scope.row.dispatchStatus" />
          </template>
        </el-table-column>
        <el-table-column label="基础工资" align="center" prop="basePay" v-if="peopleTypeValue=='在职人员'" />
        <el-table-column label="岗位津贴" align="center" prop="postAllowance" v-if="peopleTypeValue=='在职人员'" />
        <el-table-column label="其他津贴" align="center" prop="otherAllowance" v-if="peopleTypeValue=='在职人员'" />
        <el-table-column label="服装补贴" align="center" prop="clothingAllowance" v-if="peopleTypeValue=='在职人员'" />
        <el-table-column label="实发工资" align="center" prop="salaryPayable" v-if="peopleTypeValue=='在职人员'" />
        <!-- <el-table-column label="扣除餐补状态" align="center" prop="deductingMealAllowanceStatus" v-if="peopleTypeValue=='在职人员'">
          <template #default="scope">
            <dict-tag :options="data_yes_no" :value="scope.row.deductingMealAllowanceStatus" />
          </template>
        </el-table-column> -->
        <el-table-column label="请假天数" align="center" prop="leaveDays" v-if="peopleTypeValue=='在职人员'" />
        <el-table-column label="备注" align="center" prop="remark" v-if="peopleTypeValue=='在职人员'" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                style="margin-left: unset;"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:peopleInfo:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                style="margin-left: unset;"
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:peopleInfo:remove']"
              ></el-button>
            </el-tooltip>
            <span class="reContractOperate" v-if="peopleTypeValue=='在职人员'" @click="reContract(scope.row)">续约</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="peopleInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="公司名称" prop="companyId">
          <el-select class="slese" v-model="form.companyId" placeholder="请选择公司" ref="selectRef" @change="infoChanged($event)">
            <el-option
              class="communityDropdown"
              v-for="item in companyList"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectId">
          <el-select class="slese" @visible-change="communityHandleVisibleChange" v-model="form.projectId" placeholder="请选择项目" ref="selectRef">
            <el-option
              class="communityDropdown"
              v-for="item in projectList"
              :key="item.projectId"
              :label="item.projectName"
              :value="item.projectId"
            />
            <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="name">
          <el-radio-group v-model="form.sex">
            <el-radio value="男" size="large">男</el-radio>
            <el-radio value="女" size="large">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="入职时间" prop="entryTime">
          <el-date-picker
            clearable
            v-model="form.entryTime"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择入职时间"
            @change="changeContractEndDate()"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="岗位" prop="postId">
          <el-select class="slese" v-model="form.postId" placeholder="请选择岗位" ref="selectRef" @change="postChanged($event)">
            <el-option class="communityDropdown" v-for="item in postList" :key="item.postId" :label="item.post" :value="item.postId" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="identityCard">
          <el-input v-model="form.identityCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="form.address" placeholder="请输入家庭住址" />
        </el-form-item>
        <el-form-item label="是否缴纳社保" prop="isSbPayment">
          <el-radio-group v-model="form.isSbPayment">
            <el-radio value="1" size="large">是</el-radio>
            <el-radio value="0" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="社保缴纳日期" prop="sbPaymentDate">
          <el-date-picker clearable v-model="form.sbPaymentDate" type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择社保缴纳日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankNumber">
          <el-input v-model="form.bankNumber" placeholder="请输入银行卡号" />
        </el-form-item>
        <el-form-item label="合同签署次数" prop="contractCount">
          <el-input v-model="form.contractCount" placeholder="请输入合同签署次数" />
        </el-form-item>
        <el-form-item label="合同总年限" prop="contractDuration">
          <el-select v-model="form.contractDuration" placeholder="请选择合同总年限" clearable @change="changeContractEndDate()">
            <el-option v-for="dict in people_contract_duration" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同到期时间" prop="contractEndDate">
          <el-date-picker clearable v-model="form.contractEndDate" type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择合同到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="物业证件" prop="certificateId">
          <el-select class="slese" multiple v-model="form.certificateId" placeholder="请选择物业证件" ref="selectRef">
            <el-option
              class="communityDropdown"
              v-for="item in certificateList"
              :key="item.certificateId"
              :label="item.certificateName"
              :value="item.certificateId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="派遣流程" prop="dispatchStatus">
          <el-radio-group v-model="form.dispatchStatus">
            <el-radio value="1" size="large">是</el-radio>
            <el-radio value="0" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="实发工资" prop="salaryPayable">
          <el-input v-model="form.salaryPayable" placeholder="请输入基础工资" disabled />
        </el-form-item>
        <!-- <el-form-item label="扣除餐补状态" prop="deductingMealAllowanceStatus">
          <el-radio-group v-model="form.deductingMealAllowanceStatus">
            <el-radio value="1" size="large">是</el-radio>
            <el-radio value="0" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="请假天数" prop="leaveDays">
          <el-input v-model="form.leaveDays" placeholder="请输入请假天数" />
        </el-form-item>
        <el-form-item label="离职时间" prop="resignationTime" v-show="dialog.title == '修改用户信息'">
          <el-date-picker clearable v-model="form.resignationTime" type="date" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择合同到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户续约合同 -->
    <el-dialog v-model="renewalContractDialog" title="续约合同" width="500" @close="closeRenewalContractDialog">
      <el-form :model="reContractForm" ref="reContractFormRef" :rules="reContractRules">
        <el-form-item label="续约年限" prop="year">
          <el-select v-model="reContractForm.year" placeholder="请选择合同年限" clearable @change="isChangeYear(reContractForm.year)">
            <el-option v-for="dict in people_contract_year" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="减合同次数" prop="count" v-show="isNeedCount">
          <el-select v-model="reContractForm.count" placeholder="请选择修改次数" clearable>
            <el-option v-for="dict in people_contract_time" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cannelReContract">取消</el-button>
          <el-button :loading="buttonReContractLoading" type="primary" @click="commitReContract"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入数据 -->
    <el-dialog class="importData" v-model="importDataDialog" title="导入人员数据" width="500">
      <!-- <el-col :span="18"> -->
      <el-form :model="importDataForm" ref="importDataFormRef" :rules="importDataRules">
        <el-form-item label="导入公司" prop="companyId">
          <el-select class="slese" v-model="importDataForm.companyId" placeholder="请选择公司" ref="selectRef" style="width: 240px;">
            <el-option
              class="communityDropdown"
              v-for="item in companyList"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- </el-col> -->
      <!-- <el-col :span="6" class="text-center"> -->
      <div class="import-btn">
        <el-upload class="upload-demo" action=" " :limit="1" :before-upload="beforeAvatarUpload" :http-request="handleUpload" ref="fileUploadRef">
          <el-button type="primary" plain>选择文件</el-button>
        </el-upload>
      </div>
      <!-- </el-col> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cannelImportData">取消</el-button>
          <!-- <el-button :loading="buttonImportDataLoading" type="primary" @click="cannelImportData"> 确定 </el-button> -->
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PeopleInfo" lang="ts">
import { listPeopleInfo, getPeopleInfo, delPeopleInfo, addPeopleInfo, updatePeopleInfo, renewalOfContract } from '@/api/business/peopleInfo';
import { PeopleInfoVO, PeopleInfoQuery, PeopleInfoForm } from '@/api/business/peopleInfo/types';
import { listCompany } from '@/api/business/company';
import { listProject } from '@/api/business/project';
import { listPost } from '@/api/business/post';
import { listCertificate } from '@/api/business/certificate';
import useCompanyStore from '@/store/modules/company';
import { addDays } from 'date-fns';
import { formatDate } from '@/utils/index.ts'
import request from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const useCompany = useCompanyStore();
const { data_yes_no, people_contract_duration, people_contract_year,people_contract_time } = toRefs<any>(proxy?.useDict('data_yes_no','people_contract_duration','people_contract_year','people_contract_time'));

const peopleInfoList = ref<PeopleInfoVO[]>([]);
const buttonLoading = ref(false);
const buttonReContractLoading = ref(false);
const buttonImportDataLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const companyList = ref()
const projectList = ref()
const peopleTypeValue = ref('在职人员')
const options = ['在职人员', '离职人员']
const queryFormRef = ref<ElFormInstance>();
const peopleInfoFormRef = ref<ElFormInstance>();
const reContractFormRef = ref<ElFormInstance>();
const importDataFormRef = ref<ElFormInstance>();
const renewalContractDialog = ref(false)
const importDataDialog = ref(false)
const isNeedCount = ref(false)
const reContractForm = ref({
  id:undefined,
  year: undefined,
  count: undefined
})
const importDataForm = ref({
  companyId:undefined,
})

const reContractRules = ref({
  id: [
    { required: true, message: "人员ID不能为空", trigger: "blur" }
  ],
  year: [
    { required: true, message: "续约年限不能为空", trigger: "blur" }
  ]
})

const importDataRules = ref({
  companyId: [
    { required: true, message: "公司不能为空", trigger: "blur" }
  ]
})

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PeopleInfoForm = {
  id: undefined,
  companyId: undefined,
  projectId: undefined,
  name: undefined,
  identityCard: undefined,
  entryTime: undefined,
  phone: undefined,
  address: undefined,
  isSbPayment: '0',
  sbPaymentDate: undefined,
  bankNumber: undefined,
  contractEndDate: undefined,
  contractCount: 1,
  contractDuration: '1',
  certificateId: undefined,
  postId: undefined,
  basePay: undefined,
  postAllowance: undefined,
  otherAllowance: undefined,
  clothingAllowance: undefined,
  salaryPayable: undefined,
  status: '0',
  dispatchStatus: '1',
  deductingMealAllowanceStatus: undefined,
  leaveDays: undefined,
  remark: undefined,
  sex: undefined,
  resignationTime:undefined,
}
const data = reactive<PageData<PeopleInfoForm, PeopleInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    companyId: undefined,
    projectId: undefined,
    name: undefined,
    identityCard: undefined,
    entryTime: undefined,
    phone: undefined,
    address: undefined,
    isSbPayment: undefined,
    sbPaymentDate: undefined,
    bankNumber: undefined,
    contractEndDate: undefined,
    contractCount: undefined,
    contractDuration: undefined,
    certificateId: undefined,
    postId: undefined,
    basePay: undefined,
    postAllowance: undefined,
    otherAllowance: undefined,
    clothingAllowance: undefined,
    salaryPayable: undefined,
    status: undefined,
    dispatchStatus: undefined,
    deductingMealAllowanceStatus: undefined,
    leaveDays: undefined,
    remark: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "人员管理id不能为空", trigger: "blur" }
    ],
    companyId: [
      { required: true, message: "公司id不能为空", trigger: "blur" }
    ],
    projectId: [
      { required: true, message: "项目id不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    identityCard: [
      { required: true, message: "身份证号不能为空", trigger: "blur" }
    ],
    entryTime: [
      { required: true, message: "入职时间不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" }
    ],
    address: [
      { required: true, message: "家庭住址不能为空", trigger: "blur" }
    ],
    /* isSbPayment: [
      { required: true, message: "是否缴纳社保：0-否，1-是不能为空", trigger: "blur" }
    ], */
    /* sbPaymentDate: [
      { required: true, message: "社保缴纳日期不能为空", trigger: "blur" }
    ], */
    bankNumber: [
      { required: true, message: "银行卡号不能为空", trigger: "blur" }
    ],
    contractEndDate: [
      { required: true, message: "合同到期时间不能为空", trigger: "blur" }
    ],
    contractCount: [
      { required: true, message: "合同签署次数不能为空", trigger: "blur" }
    ],
    contractDuration: [
      { required: true, message: "合同年限不能为空", trigger: "blur" }
    ],
    /* certificateId: [
      { required: true, message: "证书id不能为空", trigger: "blur" }
    ], */
    postId: [
      { required: true, message: "岗位id不能为空", trigger: "blur" }
    ],
    basePay: [
      { required: true, message: "基础工资不能为空", trigger: "blur" }
    ],
    postAllowance: [
      { required: true, message: "岗位津贴不能为空", trigger: "blur" }
    ],
    otherAllowance: [
      { required: true, message: "其他津贴不能为空", trigger: "blur" }
    ],
    clothingAllowance: [
      { required: true, message: "服装补贴不能为空", trigger: "blur" }
    ],
    salaryPayable: [
      { required: true, message: "应发工资不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态：0-在职，1-离职不能为空", trigger: "change" }
    ],
    dispatchStatus: [
      { required: true, message: "派遣流程：0-否，1-是不能为空", trigger: "change" }
    ],
    /* deductingMealAllowanceStatus: [
      { required: true, message: "扣除餐补状态：0-否，1-是不能为空", trigger: "change" }
    ], */
    /* leaveDays: [
      { required: true, message: "请假天数不能为空", trigger: "blur" }
    ], */
  }
});

const { queryParams, form, rules } = toRefs(data);

const companyQueryParams = ref({
  pageNum: 1,
  pageSize: 100,
  companyId: undefined,
})

const projectQueryParams = ref({
  pageNum: 1,
  pageSize: undefined,
  companyId: undefined,
})
/* 上传文件 */
const fileUploadRef = ref<ElUploadInstance>();
/* 新增内容 */
const postList = ref()
const certificateList = ref()
const postQueryParams = ref({
  pageNum: 1,
  pageSize: 100
})
const certificateQueryParams = ref({
  pageNum: 1,
  pageSize: 100
})

/** 查询用户信息列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.status = peopleTypeValue.value == '在职人员' ? 0 : 1
  const res = await listPeopleInfo(queryParams.value);
  peopleInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 查询公司列表 */
const getCompanyList =async () => {
  companyQueryParams.value.companyId = useCompany.companyId
  const res = await listCompany(companyQueryParams.value);
  companyList.value = res.rows;
}

/* 修改公司名称 */
const infoChanged = async (id:string)=> {
  getProjectList(id)
}

/** 查询项目列表 */
const getProjectList =async (id?:any) => {
  projectQueryParams.value.companyId = id ? id : useCompany.companyId
  const projectRes = await listProject(projectQueryParams.value);
  projectList.value = projectRes.rows
}

const companyChanged = (id: any) =>{
  getProjectList(id)
}
/* 修改岗位，获取应发工资 */
const postChanged = (id:string) =>{
  postList.value.forEach((element) => {
    if(element.postId == id) {
      form.value.salaryPayable = element.salaryPayable
    }
  });
}

/* 修改合同到期时间 */
const changeContractEndDate = () =>{
  if (form.value.entryTime) {
    let timer = addDays(form.value.entryTime, form.value.contractDuration?form.value.contractDuration*1*365:365)
    let date = new Date(timer);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    form.value.contractEndDate = y + '-' + m + '-' + d + ' 00:00:00'
  } else {
    form.value.contractEndDate = undefined
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  peopleInfoFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  sessionStorage.removeItem("queryParams")
  sessionStorage.removeItem("peopleTypeValue")
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  sessionStorage.removeItem("queryParams")
  sessionStorage.removeItem("peopleTypeValue")
  queryFormRef.value?.resetFields();
  queryParams.value.companyId = useCompany.companyId ? useCompany.companyId : undefined
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: PeopleInfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  // reset();
  // dialog.visible = true;
  // dialog.title = "添加用户信息";
  router.push({ path: '/administration/peopleInfoAdd', query: { type:'add', peopleTypeValue:peopleTypeValue.value } })
}

/** 修改按钮操作 */
const handleUpdate = async (row?: PeopleInfoVO) => {
  sessionStorage.setItem("queryParams", JSON.stringify(queryParams.value));
  sessionStorage.setItem("peopleTypeValue", peopleTypeValue.value);
  // reset();
  const _id = row?.id || ids.value[0]
  // const res = await getPeopleInfo(_id);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = "修改用户信息";
  router.push({ path: '/administration/peopleInfoAdd', query: { type:'edit', id: _id, peopleTypeValue:peopleTypeValue.value} })
}

/** 提交按钮 */
const submitForm = () => {
  peopleInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let arr = JSON.parse(JSON.stringify(form.value.certificateId))
      form.value.certificateId = arr ? arr.join('、'):undefined
      buttonLoading.value = true;
      if (form.value.id) {
        await updatePeopleInfo(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("修改成功");
      } else {
        await addPeopleInfo(form.value).finally(() =>  buttonLoading.value = false);
        proxy?.$modal.msgSuccess("新增成功");
      }
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: PeopleInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户数据项？').finally(() => loading.value = false);
  await delPeopleInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 续约年限 */
const reContract = async (row?: PeopleInfoVO) => {
  renewalContractDialog.value = true
  reContractForm.value.id = row?.id
}

/** 提交续约年限 */
const commitReContract = async () => {
  reContractFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await renewalOfContract(reContractForm.value).finally(() =>  buttonReContractLoading.value = false);
      proxy?.$modal.msgSuccess("新增成功");
      cannelReContract()
      await getList();
    }
  });
}

/** 取消 */
const closeRenewalContractDialog = async () => {
  restReContract()
}

/** 取消续约年限 */
const cannelReContract = async () => {
  renewalContractDialog.value = false
  restReContract()
}

/* 重置年限内容 */
const restReContract = () => {
  reContractForm.value.id = undefined
  reContractForm.value.year = undefined
  reContractForm.value.count = undefined
  isNeedCount.value = false
  reContractFormRef.value?.resetFields();
}

/** 导出按钮操作 */
const handleExport = () => {
  let name
  let obj
  let companyName
  if(queryParams.value.companyId){
    obj = companyList.value.find(item => item.companyId === queryParams.value.companyId);
    companyName = obj.companyName
  }else{
    companyName = ''
  }
  if(queryParams.value.status == 0){
    name = '在职人员信息表'
  }else{
    name = '离职人员信息表'
  }
  proxy?.download('business/peopleInfo/export', {
    ...queryParams.value
  }, `${ companyName }${ name }_${formatDate(new Date().getTime())}.xlsx`)
}

/** 续约年限 */
const importData = async () => {
  importDataDialog.value = true
  importDataForm.value.companyId = useCompany.companyId
}

/** 取消导入数据 */
const cannelImportData = async () => {
  importDataDialog.value = false
  restImportData()
}

/* 重置导入数据 */
const restImportData = () => {
  importDataForm.value.companyId = undefined
  importDataFormRef.value?.resetFields();
  fileUploadRef.value?.clearFiles();
}

/** 上传文件前 */
const beforeAvatarUpload = (file:any) =>{
  let index = file.name.lastIndexOf('.')
  let str = file.name.substr(index + 1)
  if (!importDataForm.value.companyId) {
    ElMessage.error('请选择导入公司!')
    return false
  } else if ( ['xlsx'].indexOf(str.toLowerCase()) == -1) {
    ElMessage.error('请选择正确的文件！')
    return false
  }
  return true
}

/** 上传文件 */
const handleUpload = (file: any) => {
  let data = new FormData();
  data.append('companyId', importDataForm.value.companyId);
  data.append('file', file.file);
  let errArr: string[] = []
  let errArrObj
  request({
      url: '/business/peopleInfo/excelPeopleAll',
      headers: {
        "Content-Type": "multipart/form-data",
        isToken: true
      },
      method: 'post',
      data:data,
      onUploadProgress: function (e) {
        proxy?.$modal.loading("正在上传文件，请稍候...");
    }
  }).then(async res=> {
      if(JSON.stringify(res.data)!=='{}'){
        proxy?.$modal.closeLoading();
        fileUploadRef.value?.clearFiles();
        Object.keys(res.data).forEach(function(key) {
          var value = objectToString(res.data[key])
          errArrObj = `<strong>` + key + ': ' + `</strong>` + value + `；<br>`
          errArr.push(errArrObj)
        });
        let errRes = errArr.join('')
        await cannelImportData()
        ElMessage({
          dangerouslyUseHTMLString: true,
          message: `<div class="wrap-semicolon">${errRes}</div>`,
          type: 'error',
        })
      }else{
        proxy?.$modal.closeLoading();
        await cannelImportData()
        await getList()
      }
  }).catch(err=>{
    proxy?.$modal.closeLoading();
    cannelImportData()
    getList()
  })
  return true;
}

const objectToString = (obj) => {
  return Object.keys(obj)
    .map(key => `${key}: ${obj[key]}`)
    .join(', ');
}

/** 导出模板 */
const handleExportTemplate = () => {
  proxy?.$download.downloadTemplate('1')
}

/* -----------------弹窗内容------------------- */
/** 获取岗位列表 */
const getPostList = async () => {
  const res = await listPost(postQueryParams.value);
  postList.value = res.rows;
}

/** 获取物业证书列表 */
const getCertificateList = async () => {
  const res = await listCertificate(certificateQueryParams.value);
  certificateList.value = res.rows;
}

const isChangeYear = (data) =>{
  if(data<0){
    isNeedCount.value = true
    reContractForm.value.count = '0'
  }else{
    isNeedCount.value = false
    reContractForm.value.count = undefined
  }
}


watch([()=> useCompany.companyId,peopleTypeValue], async([newData1, newData2], [oldData1, oldData2]) => {
  if (newData1 !== oldData1) {
    queryParams.value.companyId = useCompany.companyId
    importDataForm.value.companyId = useCompany.companyId
    queryParams.value.projectId = queryParams.value.companyId ? queryParams.value.projectId : undefined
    queryParams.value.name = queryParams.value.companyId ? queryParams.value.name : undefined
    queryParams.value.isSbPayment = queryParams.value.companyId ? queryParams.value.isSbPayment : undefined
    await getCompanyList()
    await getProjectList()
    await getList()
    sessionStorage.removeItem("searchFlag")
    sessionStorage.removeItem("queryParams")
    sessionStorage.removeItem("peopleTypeValue")
  }
  if (newData2 && oldData2 && newData2 !== oldData2) {
    await getList()
  }
},{ deep:true, immediate: true });

onMounted(async() => {
  if (window.history.state.back.includes('/administration/peopleInfoAdd')) {
    if (sessionStorage.getItem("searchFlag")=='0') {
      //如果有就读取缓存里面的数据
      queryParams.value = await JSON.parse(sessionStorage.getItem("queryParams")) ? JSON.parse(sessionStorage.getItem("queryParams")) : queryParams.value
      peopleTypeValue.value = await sessionStorage.getItem("peopleTypeValue") ? sessionStorage.getItem("peopleTypeValue") : peopleTypeValue.value
    } else {
      sessionStorage.removeItem("queryParams")
      sessionStorage.removeItem("peopleTypeValue")
    }
  } else {
    sessionStorage.removeItem("searchFlag")
    sessionStorage.removeItem("queryParams")
    sessionStorage.removeItem("peopleTypeValue")
  }
  await getCompanyList();
  await getProjectList();
  await getList();
  await getPostList()
  await getCertificateList()
  window.addEventListener('beforeunload', function (e) {
    sessionStorage.removeItem("searchFlag")
    sessionStorage.removeItem("queryParams")
    sessionStorage.removeItem("peopleTypeValue")
  });
});
</script>
<style>
.peopleInfoSearch .el-form--inline .el-form-item {
  align-items: center;
}
.reContractOperate {
  color: #409EFF;
  margin: 0 5px;
  cursor: pointer;
}
.wrap-semicolon{
  line-height: 1.5;
}
</style>
